﻿using System;
using NopSolutions.NopCommerce.Common.Utils;

namespace NopSolutions.NopCommerce.Web.Modules
{
    public partial class UserAgreementControl : BaseNopFrontendUserControl
    {
        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            Load += new EventHandler(UserAgreementControl_Load);
            PreRender += new EventHandler(UserAgreementControl_PreRender);
            btnContinue.Click += new EventHandler(btnContinue_Click);
        }

        void UserAgreementControl_Load(object sender, EventArgs e) {
            if (!this.OrderProductVariantGuid.HasValue) {
                Response.Redirect(CommonHelper.GetStoreLocation());
            }

            var opv = this.OrderService.GetOrderProductVariantByGuid(this.OrderProductVariantGuid.Value);
            if (opv == null) {
                Response.Redirect(CommonHelper.GetStoreLocation());
            }

            var productVariant = this.ProductService.GetProductVariantById(opv.ProductVariantId);
            if (productVariant == null || !productVariant.HasUserAgreement) {
                Response.Redirect(CommonHelper.GetStoreLocation());
            }

            lblUserAgreementText.Text = productVariant.UserAgreementText;
        }

        void UserAgreementControl_PreRender(object sender, EventArgs e) {
            this.cbIsAgree.Attributes.Add("onclick", "toggleContinueButton();");
        }

        protected void btnContinue_Click(object sender, EventArgs e) {
            if (cbIsAgree.Checked) {
                if (!this.OrderProductVariantGuid.HasValue) {
                    Response.Redirect(CommonHelper.GetStoreLocation());
                }

                var opv = this.OrderService.GetOrderProductVariantByGuid(this.OrderProductVariantGuid.Value);
                if (opv != null) {
                    string url = this.DownloadService.GetDownloadUrl(opv);
                    url = CommonHelper.ModifyQueryString(url, "Agree=true", null);
                    Response.Redirect(url);
                }
            }
        }

        public Guid? OrderProductVariantGuid {
            get {
                return CommonHelper.QueryStringGuid("OrderProductVariantGUID");
            }
        }
    }
}